define(function (require, exports, module) {

    require("apps/grid");
    require("apps/easyui");


    exports.init = function (ctx, uuid) {

        require("zrender/zrender");
        var ec = require("echarts/echarts");
        var theme = require("echarts/theme/macarons");
        var myChart = ec.init(document.getElementById("echartPie"), theme);
        $("#globContent").on("resize", myChart.resize);
        $(window).on("resize", myChart.resize);

        function renderBar(data){
            var option = {
                title : {
                    text: '数据统计'
                },
                tooltip : {
                    trigger: 'axis',
                    axisPointer : {            // 坐标轴指示器，坐标轴触发有效
                        type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                dataZoom: data.dataZoom,
                legend: {
                    x: 110,
                    data: data.legend
                },
                toolbox: {
                    show : true,
//                y: 'center',
                    feature : {
                        saveAsImage : {show: true}
                    }
                },
                xAxis : [
                    {
                        type : 'category',
                        axisLabel: {
                            interval: 0
                        },
                        data : data.xAxis
                    }
                ],
                yAxis : [
                    {
                        type : 'value',
                        name: '（天）'
//                    axisLabel : {
//                        formatter: '{value} 天'
//                    }
                    }
                ],
                series : data.series
            };
            myChart.clear();
            myChart.setOption(option);
        }

        function renderPie(data){
            var option = {
                title : {
                    text: '数据统计',
                    x: 'center'
                },
                tooltip : {
                    trigger: 'item',
                    formatter: "{a} <br/>{b} : {c}天 ({d}%)"
                },
                toolbox: {
                    show : true,
                    feature : {
//                    restore : {show: true},
                        saveAsImage : {show: true}
                    }
                },
                legend: {
                    orient : 'vertical',
                    x : 'left',
                    data: data.legend
                },
                series : [
                    {
                        name:'考勤事由',
                        type:'pie',
                        radius : '70%',
                        center: ['50%', '55%'],
                        selectedMode: 'single',
                        itemStyle : {
                            normal : {
                                label : {
                                    position : 'outer',
                                    formatter : function (params) {
                                        return params.name + "(" + params.value + "天)";
                                    }
                                },
                                labelLine : {
                                    show : true
                                }
                            }
                        },
                        data: data.data
                    }
                ]
            };
            myChart.clear();
            myChart.setOption(option);
        }

        var pageListComponent = new $.PageListComponent(uuid, {
            view: {
                grid: "grid",
                myToolbar: "nsdb",
                colbar: "attendance_tempate"
            },
            configs: {
                gridUrl: ctx + '/app/api/attendance/countList',
                queryParams: $("[data-id=conditionForm]").serializeJson(),
                gridColumns: [
                    {
                        field: 'id',
                        checkbox: true
                    },
                    {
                        field: 'reason.dirValue',
                        title: '考勤事由',
                        width: 90,
                        align: 'center'

                    },
                    {
                        field: 'remark',
                        title: '备注',
                        width: 160,
                        align: 'center'

                    },
//                    {
//                        field: 'applyUser.sysOrganizations',
//                        title: '所属科室',
//                        width: 90,
//                        align: 'center',
//                        formatter: function(value, row, index){
//                            if(!value.length){
//                                return "暂无";
//                            }
//                            return value[0].depBelong.dirValue;
//                        }
//                    },
                    {
                        field: 'applyUser.orgsDescription',
                        title: '所属小组',
                        width: 90,
                        align: 'center',
                        formatter: function(value, row, index){
                            if(value == ""){
                                return "暂无";
                            }
                            return value;
                        }
                    },
                    {
                        field: 'applyUser.userName',
                        title: '人员',
                        width: 90,
                        align: 'center'
                    },
                    {
                        field: 'createUser.userName',
                        title: '填报人',
                        width: 100,
                        align: 'center',
                        formatter: function(value, row, index){
                            if(row.isReplace == 1){
                                return value + "(代填)"
                            }
                            return value;
                        }
                    },
                    {
                        field: 'createTime',
                        title: '填报时间',
                        width: 130,
                        align: 'center'
                    },
                    {
                        field: 'beginTime',
                        title: '开始时间',
                        width: 130,
                        align: 'center'
                    },
                    {
                        field: 'endTime',
                        title: '结束时间',
                        width: 130,
                        align: 'center',
                        formatter: function(value, row, index){
                            if(value == null){
                                return "暂无";
                            }
                            return value;
                        }
                    },
                    {
                        field: 'hourOrDay',
                        title: '小计',
                        width: 100,
                        align: 'center',
                        formatter: function(value, row, index){
                            if(value == null){
                                return "暂无";
                            }
                            return value;
                        }
                    }
                ]
            },
            events: {
                renderColBarBefore: function (type, row) {
                    return true;
                },
                onClickColBtn: function (context, btn, row) {
                    switch (btn.key) {
                        case "edit":
                            whenEdit(context, btn.href, row.id);
                            break;
                        case "view":
//                            context.detail('考勤记录详情', row);
                            whenView(context, btn.href, row.id);
                            break;
                        default :
                            break;
                    }
                },
                onClickToolbarBtn: function (context, btn) {
                    switch (btn.key) {
                        case "export":
                            whenExport(btn.href);
                            break;
                        case "exportCount":
                            whenExportCount(btn.href);
                            break;
                        case "exportSumCount":
                            whenExportSumCount(btn.href);
                            break;
                        case "exportSumOverwork":
                            whenExportSumOverwork(btn.href);
                            break;
//                        case "exportOverWork":
//                            whenExportOverWork(btn.href);
//                            break;
                        case "del":
//                            context.del(btn.href);
                            whenDel(context, btn.href);
                            break;
                        default :
                            break;
                    }
                }
            }
        });

        var contextWindow = new $.PageWindow();

        var page = new $.PageDomFactory(uuid, true);

        function whenEdit(context, href, id) {
            contextWindow.create({
                href: href + "?id=" + id,
                method: "attendance_edit_save",
                title: "编辑考勤记录",
                height: 520,
                callback: function (status) {
                    if (status) {
//                        context.grid.datagrid("reload");
                        dataCount("reload");
                    }
                }
            });
            contextWindow.open();
        }

        function whenView(context, href, id){
            contextWindow.create({
                href: href + "?id=" + id,
                title: "考勤记录详情",
                width: 500
            });
            contextWindow.open();
        }

        function whenExport(href){
            var template = "序号=id=string;考勤事由=reason.dirValue=string;备注=remark=string;" +
                "所属小组=applyUser.orgsDescription=string;人员=applyUser.userName=string;" +
                "填报人=createUser.userName=string;填报时间=createTime=date[yyyy-MM-dd HH:mm];" +
                "开始时间=beginTime=date[yyyy-MM-dd HH:mm];结束时间=endTime=date[yyyy-MM-dd HH:mm];" +
                "小时数=hours=date[HH:mm];天数=days=string";
            var form = page.getJqDom("conditionForm");
            var action = form.attr("action");
            form.attr("action", href);
            page.getJqDom("template").attr("value", template);
            form.submit();
            form.attr("action", action);
            page.getJqDom("template").attr("value", "");
        }

        function whenExportCount(href){
            var template = "序号=id=string;人员=user=string;所属小组=group=string;公干(H)=gongganH=string;" +
                "公干=gongganD=string;零星事假(H)=lingxingH=string;零星事假=lingxingD=string;加班(H)=jiabanH=string;" +
                "加班=jiabanD=string;换休=huanxiu=string;出差=chuchai=string;有薪事假=youxinshijia=string;" +
                "无薪事假=wuxinshijia=string;病假=bingjia=string;产假=chanjia=string;婚丧假=hunsangjia=string;" +
                "工伤假=gongshangjia=string;工龄假=gonglingjia=string;职称假=zhichengjia=string;有害假=youhaijia=string;" +
                "探亲假=tanqinjia=string;请假总计=holiday1=string;请假总计(不含零星)=holiday2=string;";
            var form = page.getJqDom("conditionForm");
            var action = form.attr("action");
            form.attr("action", href);
            page.getJqDom("template").attr("value", template);
            form.submit();
            form.attr("action", action);
            page.getJqDom("template").attr("value", "");
        }

        function whenExportSumCount(href){
            var template = "序号=id=string;单位=org=string;姓名=user=string;所属小组=group=string;" +
                "何种缺勤=reasonStr=string;缺勤时间=timeStr=string;累计=totalTime=string;";
            var form = page.getJqDom("conditionForm");
            var action = form.attr("action");
            form.attr("action", href);
            page.getJqDom("template").attr("value", template);
            form.submit();
            form.attr("action", action);
            page.getJqDom("template").attr("value", "");
        }

        function whenExportSumOverwork(href){
            var template = "序号=id=string;姓名=user=string;所属小组=group=string;" +
                "加班内容=reasonStr=string;加班工时(H)=jiabanH=string;备注=totalTime=string;";
            var form = page.getJqDom("conditionForm");
            var action = form.attr("action");
            form.attr("action", href);
            page.getJqDom("template").attr("value", template);
            form.submit();
            form.attr("action", action);
            page.getJqDom("template").attr("value", "");
        }

//        function whenExportOverWork(href){
//            var template = "序号=id=string;小组=applyUser.orgsDescription=string;人员=applyUser.userName=string;" +
//                "加班日期=beginTime=date[yyyy年MM月dd日];项目代号=projectCode=string;加班内容=remark=string;" +
//                "起止时间=fromTo=string;工时(H)=workHours=string;";
//            var form = page.getJqDom("conditionForm");
//            var action = form.attr("action");
//            form.attr("action", href);
//            page.getJqDom("template").attr("value", template);
//            form.submit();
//            form.attr("action", action);
//            page.getJqDom("template").attr("value", "");
//        }

        function whenDel(context, href) {
            var rows = context.grid.datagrid('getChecked');
            if (rows.length == 0) {
                $.messager.alert('信息', '请先选择一行', 'info');
                context.grid.datagrid('clearSelections');
                return;
            }
            if (rows.length > 0) {
                $.messager.confirm('确定', '确定要删除吗?', function (result) {
                    if (result) {
                        var ids = [];
                        for (var i = 0; i < rows.length; i++) {
                            ids.push(rows[i].id);
                        }
                        $.post(
                            href,
                            $.utils.buildJson({ids: ids}),
                            function (json) {
                                if ($.isErrorRequest(json)) {
                                    $.messager.alert('信息', json.msg, 'info');
                                } else {
                                    $.messager.alert('信息', '删除成功', 'info');
                                    dataCount("reload");
                                }
                            }
                        );
                    }
                });
            }
        };

        page.getJqDom("year").combobox({
            editable: false,
            onSelect: function(record){
                if(record.value == ''){
                    page.getJqDom("month").combobox('setValue', "");
                }
                dataCount("load");
            }
        });
        page.getJqDom("month").combobox({
            editable: false,
            onSelect: function(){
                dataCount("load");
            }
        });
        page.getJqDom("dep").combobox({
            editable: false
        });
        page.getJqDom("user").combobox({
            editable: false,
            valueField: "id",
            textField: "userName",
//            data: [{id: "", userName: "全部"}],
            url: ctx + "/app/api/sysMember/showOrgUsers",
            loadFilter: function (data) {
                data.unshift({id: "", userName: "全部"});
                return data;
            },
            onSelect: function(){
                dataCount("load");
            }
        });
        page.getJqDom("org").combobox({
            editable: false,
            onSelect: function(record){
                page.getJqDom("user").combobox({
                    url: ctx + "/app/api/sysMember/showOrgUsers?orgId=" + record.value,
                    loadFilter: function (data) {
                        data.unshift({id: "", userName: "全部"});
                        return data;
                    }
                });
                dataCount("load");
            }
        });
        page.getJqDom("reason").combobox({
            editable: false,
            onSelect: function(){
                var postData = page.getJqDom("conditionForm").serializeJson();
                pageListComponent.grid.datagrid("load", postData);
            }
        });

        function dataCount(mode){
            var postForm = page.getJqDom("conditionForm");
            var postData = postForm.serializeJson();
            $("body").wait("start", "查询中,请稍候.");
            $.post(postForm.attr("action") + "?random=" + Math.random(),
                $.utils.buildJson(postData),
                function(json){
                    $("body").wait("end");
                    if(json.chartType == "pie"){
                        renderPie(json);
                    }else{
                        renderBar(json);
                    }
                }, "json");
            pageListComponent.grid.datagrid(mode, postData);
        }

        function dataCountInit(){
            var postForm = page.getJqDom("conditionForm");
            var postData = postForm.serializeJson();
            $("body").wait("start", "查询中,请稍候.");
            $.post(postForm.attr("action") + "?random=" + Math.random(),
                $.utils.buildJson(postData),
                function(json){
                    $("body").wait("end");
                    if(json.chartType == "pie"){
                        renderPie(json);
                    }else{
                        renderBar(json);
                    }
                }, "json");
        }
        dataCountInit();

    };

    exports.update = function (ctx, uuid, config) {
        var page = new $.PageDomFactory(uuid, true);
        page.getJqDom("form-attendance-update-info").find(".easyui-validatebox").validatebox();

        page.getJqDom("reason").combobox({
            loadFilter: function (data) {
                return data.content;
            },
            url: ctx + "/app/api/directory/list?dirGroup=DIRECTORY_REASON_TYPE",
            valueField: 'id',
            textField: 'dirValue',
            value: config.reasonId,
            onSelect: function(record){
//                if(record.dirValue == "加班"){
//                    page.getJqDom("pCodeItem").show();
//                    page.getJqDom("projectCode").validatebox("enableValidation");
//                }else{
//                    page.getJqDom("pCodeItem").hide();
//                    page.getJqDom("projectCode").val("");
//                    page.getJqDom("projectCode").validatebox("disableValidation");
//                }

                if(record.dirValue == "加班" || record.dirValue == "公干" || record.dirValue == "零星事假"){
                    page.getJqDom("beginTime1").datebox("disable");
                    page.getJqDom("hourBegin").show();
                    page.getJqDom("dayBegin").hide();
                    page.getJqDom("endTime").datetimebox("enable");
                    page.getJqDom("days").numberbox("disable");
                }else{
                    page.getJqDom("beginTime1").datebox("enable");
                    page.getJqDom("hourBegin").hide();
                    page.getJqDom("dayBegin").show();
                    page.getJqDom("endTime").datetimebox("disable");
                    page.getJqDom("days").numberbox("enable");
                }
            }
        });

        page.getJqDom("createTime").datetimebox({
            showSeconds: false
        });

        page.getJqDom("beginTime").datetimebox({
            showSeconds: false
        });

        page.getJqDom("beginTime1").datebox();
        page.getJqDom("apm").combobox({
            editable: false
        });

        page.getJqDom("endTime").datetimebox({
            showSeconds: false
        });

//        pCodeItem();
//
//        function pCodeItem(){
//            if(config.projectCode == null || config.projectCode == ""){
////                page.getJqDom("pCodeItem").hide();
//                page.getJqDom("projectCode").validatebox("disableValidation");
//            }else{
////                page.getJqDom("pCodeItem").show();
//                page.getJqDom("projectCode").validatebox("enableValidation");
//            }
//        }

        window.attendance_edit_save = function (win) {
            var postForm = page.getJqDom("form-attendance-update-info");
            if (!postForm.form('validate')) {
                return false;
            }
            var postData = postForm.serializeJson();
            win.wait("start", "保存中,请稍候.");
            $.post(postForm.attr("action")
                    + "?random=" + Math.random(), $.utils.buildJson(postData),
                function (json) {
                    win.wait("end");
                    if ($.isPlainObject(json) && json.error) {
                        $.messager.alert('信息',
                            json.msg, 'info');
                        win.callback(false);
                    } else {
                        $.messager.alert('信息',
                            '保存成功', 'info');
                        win.callback(true);
                        win.close();
                    }
                }, "json");
        }
    };


//        //嵌套环饼图
//        var option = {
//            title : {
//                text: '数据统计',
//                x: 'left'
//            },
//            tooltip : {
//                trigger: 'item',
//                formatter: "{a} <br/>{b} : {c}天 ({d}%)"
//            },
//            toolbox: {
//                show : true,
//                feature : {
//                    restore : {show: true},
//                    saveAsImage : {show: true}
//                }
//            },
//            series : [
//                {
//                    name:'数据分布',
//                    type:'pie',
//                    selectedMode: 'single',
//                    radius : [0, 70],
//
//                    // for funnel
//                    x: '20%',
//                    width: '40%',
//                    funnelAlign: 'right',
//                    max: 1548,
//
//                    itemStyle : {
//                        normal : {
//                            label : {
//                                position : 'inner',
//                                formatter : function (params) {
//                                    return params.name + "(" + params.value + "天)";
//                                }
//                            },
//                            labelLine : {
//                                show : false
//                            }
//                        }
//                    },
//                    data: data.in
//                },
//                {
//                    name:'考勤事由',
//                    type:'pie',
//                    radius : [100, 140],
//
//                    // for funnel
//                    x: '60%',
//                    width: '35%',
//                    funnelAlign: 'left',
//                    max: 1048,
//
//                    itemStyle : {
//                        normal : {
//                            label : {
//                                position : 'outer',
//                                formatter : function (params) {
//                                    return params.name + "(" + params.value + "天)";
//                                }
//                            },
//                            labelLine : {
//                                show : true
//                            }
//                        }
//                    },
//                    data: data.out
//                }
//            ]
//        };

});